<template>
  <div class="user-container">
    <div class="table-operations">
      <a-space>
        <a-input-search
          v-model:value="searchText"
          placeholder="搜索用户"
          style="width: 200px"
          @search="onSearch"
        />
        <a-button type="primary" @click="showModal()">
          <template #icon><plus-outlined /></template>
          添加用户
        </a-button>
      </a-space>
    </div>

    <a-table :columns="columns" :data-source="data" :loading="loading">
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'status'">
          <a-tag :color="record.status === '启用' ? 'green' : 'red'">
            {{ record.status }}
          </a-tag>
        </template>
        <template v-else-if="column.key === 'action'">
          <a-space>
            <a @click="showModal(record)">编辑</a>
            <a-divider type="vertical" />
            <a-popconfirm
              title="确定要删除这个用户吗？"
              @confirm="handleDelete(record.key)"
            >
              <a>删除</a>
            </a-popconfirm>
          </a-space>
        </template>
      </template>
    </a-table>

    <a-modal
      v-model:visible="modalVisible"
      :title="currentRecord ? '编辑用户' : '添加用户'"
      @ok="handleOk"
    >
      <a-form
        ref="formRef"
        :model="formState"
        :rules="rules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-form-item label="用户名" name="username">
          <a-input v-model:value="formState.username" />
        </a-form-item>
        <a-form-item
          label="密码"
          name="password"
          :rules="[{ required: !currentRecord, message: '请输入密码!' }]"
        >
          <a-input-password v-model:value="formState.password" />
        </a-form-item>
        <a-form-item label="邮箱" name="email">
          <a-input v-model:value="formState.email" />
        </a-form-item>
        <a-form-item label="状态" name="status">
          <a-select v-model:value="formState.status">
            <a-select-option value="启用">启用</a-select-option>
            <a-select-option value="禁用">禁用</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, inject, onMounted, onUnmounted } from 'vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'

// 注入事件总线
const emitter = inject('emitter')

// 处理来自聊天组件的消息
const handlePageAction = (action) => {
  if (action.type === 'chat-command') {
    const message = action.data
    const content = message.content.toLowerCase()
    
    // 根据聊天内容执行不同操作
    if (content.includes('搜索用户') || content.includes('查找用户')) {
      // 提取搜索关键词
      const keyword = content.replace(/搜索用户|查找用户/g, '').trim()
      if (keyword) {
        searchText.value = keyword
        onSearch(keyword)
        message.success(`正在搜索用户: ${keyword}`)
      }
    } else if (content.includes('添加用户') || content.includes('新增用户')) {
      showModal()
      message.success('已打开添加用户表单')
    }
  }
}

// 组件挂载时添加事件监听
onMounted(() => {
  emitter.on('page-action', handlePageAction)
})

// 组件卸载时移除事件监听
onUnmounted(() => {
  emitter.off('page-action', handlePageAction)
})

const columns = [
  {
    title: '用户名',
    dataIndex: 'username',
    key: 'username',
  },
  {
    title: '邮箱',
    dataIndex: 'email',
    key: 'email',
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
  },
  {
    title: '操作',
    key: 'action',
  },
]

const data = ref([
  {
    key: '1',
    username: 'admin',
    email: 'admin@example.com',
    status: '启用',
    createTime: '2023-09-01 10:00:00',
  },
  {
    key: '2',
    username: 'user1',
    email: 'user1@example.com',
    status: '启用',
    createTime: '2023-09-01 11:00:00',
  },
])

const loading = ref(false)
const searchText = ref('')
const modalVisible = ref(false)
const currentRecord = ref(null)
const formRef = ref()

const formState = reactive({
  username: '',
  password: '',
  email: '',
  status: '启用',
})

const rules = {
  username: [{ required: true, message: '请输入用户名!' }],
  email: [{ required: true, message: '请输入邮箱!', type: 'email' }],
  status: [{ required: true, message: '请选择状态!' }],
}

const showModal = (record = null) => {
  currentRecord.value = record
  if (record) {
    Object.assign(formState, record)
  } else {
    Object.assign(formState, {
      username: '',
      password: '',
      email: '',
      status: '启用',
    })
  }
  modalVisible.value = true
}

const handleOk = () => {
  formRef.value.validate().then(() => {
    if (currentRecord.value) {
      const index = data.value.findIndex(item => item.key === currentRecord.value.key)
      data.value[index] = { ...formState, key: currentRecord.value.key }
      message.success('更新成功')
    } else {
      data.value.push({
        ...formState,
        key: String(data.value.length + 1),
        createTime: new Date().toLocaleString(),
      })
      message.success('添加成功')
    }
    modalVisible.value = false
  })
}

const handleDelete = (key) => {
  data.value = data.value.filter(item => item.key !== key)
  message.success('删除成功')
}

const onSearch = (value) => {
  console.log('search:', value)
}
</script>

<style lang="less" scoped>
.user-container {
  .table-operations {
    margin-bottom: 16px;
  }
}
</style>